package com.mop.app.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mop.app.common.BaseController;
import com.mop.app.common.PageQueryWrapper;
import com.mop.app.common.enums.AppBizEnums;
import com.mop.app.dal.entity.AppSourceCategory;
import com.mop.app.service.AppSourceCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 资源类目
 *
 * @author wchen
 * @since 2020-02-27
 */
@RestController
@RequestMapping("/open/file")
public class FileController extends BaseController {

    @Autowired
    private AppSourceCategoryService appSourceCategoryService;


    /**
     * 资源类别分页查询
     *
     * @param query 默认使用实体作为查询参数，可根据业务需要替换为查询对象，如若替换为查询对象，请修改相应mapper文件的sql查询
     * @return 分页结果集
     */
    @PostMapping("/list")
    public Page<AppSourceCategory> list(@RequestBody PageQueryWrapper<AppSourceCategory> query) {

        query.setQueryClazz(AppSourceCategory.class);
        Page pageList = appSourceCategoryService.pageQuery(query);

        return pageList;
    }

    @PostMapping("upload.do")
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request)
            throws IllegalStateException, IOException {
        System.out.println("UploadController.upload()");

        // 判断上传的文件是否为空
        boolean isEmpty = file.isEmpty();
        AppBizEnums.ERROR_1009.assertTrue(!isEmpty);

        // 检查文件大小
        long fileSize = file.getSize();
        System.out.println("\tsize=" + fileSize);
        if (fileSize > 1 * 1024 * 1024) {
            throw new RuntimeException("上传失败！上传的文件大小超出了限制！");
        }
        AppBizEnums.ERROR_1009.assertTrue(fileSize < 1 * 1024 * 1024);


        // 检查文件MIME类型
        String contentType = file.getContentType();
        System.out.println("\tcontentType=" + contentType);

        Set<String> types = new HashSet<>();
        types.add("image/jpeg");
        types.add("image/png");
        types.add("image/gif");
        AppBizEnums.ERROR_1010.assertTrue(types.contains(contentType));

        // 准备文件夹,获取项目中upload文件夹的路径
        String parentDir = request.getServletContext().getRealPath("upload");
        // request.getSession().getServletContext().getRealPath("");
        // request.getRealPath("");
        System.out.println("\tpath=" + parentDir);
        File parent = new File(parentDir);
        if (!parent.exists()) {
            parent.mkdirs();
        }

        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        System.out.println("\toriginalFilename=" + originalFilename);

        // 确定最终保存时使用的文件
        String filename = UUID.randomUUID().toString();
        String suffix = "";
        int beginIndex = originalFilename.lastIndexOf(".");
        if (beginIndex != -1) {
            suffix = originalFilename.substring(beginIndex);
        }

        // 执行保存文件
        File dest = new File(parent, filename + suffix);
        file.transferTo(dest);

        return "OK";
    }

}

